package cn.edu.nju.software.android.model;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import cn.edu.nju.software.android.activity.MainActivity;
import cn.edu.nju.software.android.util.DateHelper;

import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.StatusesAPI;
import com.weibo.sdk.android.api.WeiboAPI;
import com.weibo.sdk.android.net.RequestListener;

public class Status implements Serializable{
	public static StatusesAPI api = new StatusesAPI(MainActivity.accessToken);
	private static final long serialVersionUID = 1416154929400038722L;
	private Date createdAt;
	private long id;
	private String text;
	private String thumbnail_pic;
	private String bmiddle_pic;
	private String original_pic;
	private User user;
	private Status retweetStatus;
	private int commentsCount;
	private int repostsCount;
	private String source;
	private String lat;
	private String lon;
	private String picFile;

	private Geo geo;

	public Status(String text, String lat, String lon){
		this.text = text;
		this.lat = lat;
		this.lon = lon;
	}

	public Status(String text, String lat, String lon, String picFile){
		this.text = text;
		this.lat = lat;
		this.lon = lon;
		this.setPicFile(picFile);
	}

	public Status(JSONObject json){
		try {
			id = json.getLong("id");
			text = json.getString("text");
			createdAt = DateHelper.parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
			if(!json.isNull("thumbnail_pic")){
				thumbnail_pic = json.getString("thumbnail_pic");
			}
			if(!json.isNull("bmiddle_pic")){
				bmiddle_pic = json.getString("bmiddle_pic");
			}
			if(!json.isNull("original_pic")){
				original_pic = json.getString("original_pic");
			}
			if(!json.isNull("user")){
				user = new User(json.getJSONObject("user"));
			}
			if(!json.isNull("retweeted_status")){
				retweetStatus = new Status(json.getJSONObject("retweeted_status"));
			}
			if(!json.isNull("geo")){
				geo = new Geo(json.getJSONObject("geo"));
			}
			if(!json.isNull("comments_count"))
				commentsCount = json.getInt("comments_count");
			if(!json.isNull("reposts_count"))
				repostsCount = json.getInt("reposts_count");
			if(!json.isNull("source")){
				source = json.getString("source");
				Pattern p = Pattern.compile("(<a.*>)(.+)(</a>)");
				Matcher m = p.matcher(source);
				if(m.find()){
					source = m.group(2);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	public static List<Status> constructStatuses(String res) {
		ArrayList<Status> statuses = new ArrayList<Status>();
		JSONArray json;
		try {
			JSONObject object = new JSONObject(res);
			json = object.getJSONArray("statuses");
			for (int i = 0; i < json.length(); i++) {
				Status s = new Status(json.getJSONObject(i));
				statuses.add(s);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return statuses;
	}

	public Date getCreatedAt() {
		return createdAt;
	}

	public void setCreatedAt(Date createdAt) {
		this.createdAt = createdAt;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public String getThumbnail_pic() {
		return thumbnail_pic;
	}

	public void setThumbnail_pic(String thumbnail_pic) {
		this.thumbnail_pic = thumbnail_pic;
	}

	public String getBmiddle_pic() {
		return bmiddle_pic;
	}

	public void setBmiddle_pic(String bmiddle_pic) {
		this.bmiddle_pic = bmiddle_pic;
	}

	public String getOriginal_pic() {
		return original_pic;
	}

	public void setOriginal_pic(String original_pic) {
		this.original_pic = original_pic;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Status getRetweetStatus() {
		return retweetStatus;
	}

	public void setRetweetStatus(Status retweetStatus) {
		this.retweetStatus = retweetStatus;
	}

	public int getCommentsCount() {
		return commentsCount;
	}

	public void setCommentsCount(int commentsCount) {
		this.commentsCount = commentsCount;
	}

	public int getRepostsCount() {
		return repostsCount;
	}

	public void setRepostsCount(int repostsCount) {
		this.repostsCount = repostsCount;
	}

	public String getSource() {
		return source;
	}

	public void setSource(String source) {
		this.source = source;
	}

	public String getLat() {
		return lat;
	}

	public void setLat(String lat) {
		this.lat = lat;
	}

	public String getLon() {
		return lon;
	}

	public void setLon(String lon) {
		this.lon = lon;
	}

	public String getPicFile() {
		return picFile;
	}

	public void setPicFile(String picFile) {
		this.picFile = picFile;
	}

	public Geo getGeo() {
		return geo;
	}

	public void setGeo(Geo geo) {
		this.geo = geo;
	}

	public static void downloadNewestStatus(long sinceId, final List<Status> statuses, final Handler handler) {
		api.homeTimeline(sinceId, 0, 20, 1, false, WeiboAPI.FEATURE.ALL, false, new RequestListener() {

			@Override
			public void onIOException(IOException e) {

			}

			@Override
			public void onError(WeiboException e) {
				e.printStackTrace();
			}

			@Override
			public void onComplete(String response) {
				List<Status> newStatuses = Status.constructStatuses(response);
				for(int i = newStatuses.size() - 1; i >= 0 ; i--){
					statuses.add(0, newStatuses.get(i));
				}
				handler.sendEmptyMessage(0);
			}
		});
	}

	public static void downloadMoreStatus(long max_id, final List<Status> statuses, final Handler handler) {
		api.homeTimeline(0, max_id, 20, 1, false, WeiboAPI.FEATURE.ALL, false, new RequestListener() {

			@Override
			public void onIOException(IOException e) {

			}

			@Override
			public void onError(WeiboException e) {

			}

			@Override
			public void onComplete(String response) {
				List<Status> newStatuses = Status.constructStatuses(response);
				for(int i = 0; i < newStatuses.size() ; i++){
					statuses.add(newStatuses.get(i));
				}
				handler.sendEmptyMessage(0);
			}
		});
	}

	public static void downloadMorePersonalStatus(long uid, long since_id, final List<Status> statuses, final Handler handler){
		api.userTimeline(uid, since_id, 0, 50, 1, false, WeiboAPI.FEATURE.ALL, false, new RequestListener() {

			@Override
			public void onIOException(IOException e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onError(WeiboException e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onComplete(String response) {
				List<Status> newStatuses = Status.constructStatuses(response);
				for(int i = 0; i < newStatuses.size() ; i++){
					statuses.add(newStatuses.get(i));
				}
				handler.sendEmptyMessage(newStatuses.size());
			}
		});
	}

	public static void getNewestMentionMeStatus(final long since_id, final List<Status> statuses, final Handler handler){
		api.mentions(since_id, 0, 50, 1,  WeiboAPI.AUTHOR_FILTER.ALL, WeiboAPI.SRC_FILTER.ALL, WeiboAPI.TYPE_FILTER.ALL,false, new RequestListener() {

			@Override
			public void onIOException(IOException e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onError(WeiboException e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onComplete(String response) {
				int newNum = 0;
				List<Status> newStatuses = Status.constructStatuses(response);
				for(int i = newStatuses.size()-1; i >= 0 ; i--){
					Status status = newStatuses.get(i);
					if(status.getId() != since_id){
						newNum++;
						statuses.add(0, status);
					}
				}
				Message msg = new Message();
				Bundle bundle = new Bundle();
				bundle.putInt("num", newNum);
				msg.setData(bundle);
				handler.sendMessage(msg);

			}
		});
	}

	public static void getMoreMentionMeStatus(final long max_id, final List<Status> statuses, final Handler handler){
		api.mentions(0, max_id, 50, 1,  WeiboAPI.AUTHOR_FILTER.ALL, WeiboAPI.SRC_FILTER.ALL, WeiboAPI.TYPE_FILTER.ALL,false, new RequestListener() {

			@Override
			public void onIOException(IOException e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onError(WeiboException e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onComplete(String response) {
				int newNum = 0;
				List<Status> newStatuses = Status.constructStatuses(response);
				for(int i = 0; i < newStatuses.size() ; i++){
					Status status = newStatuses.get(i);
					if(status.getId() != max_id){
						newNum++;
						statuses.add(status);
					}
				}
				Message msg = new Message();
				Bundle bundle = new Bundle();
				bundle.putInt("num", newNum);
				msg.setData(bundle);
				handler.sendMessage(msg);

			}
		});
	}


	public void postNewStatus(final Handler handler) {
		api.update(text, lat, lon, new RequestListener() {

			@Override
			public void onIOException(IOException e) {

			}

			@Override
			public void onError(WeiboException e) {

			}

			@Override
			public void onComplete(String response) {
				handler.sendEmptyMessage(0);
			}
		});
	}

	public void repost(long id, final Handler handler){
		api.repost(id, text, WeiboAPI.COMMENTS_TYPE.BOTH, new RequestListener() {

			@Override
			public void onIOException(IOException e) {
				e.printStackTrace();

			}

			@Override
			public void onError(WeiboException e) {
				e.printStackTrace();
			}

			@Override
			public void onComplete(String response) {
				handler.sendEmptyMessage(0);
			}
		});
	}

	public void upload(String fileName, final Handler handler){
		api.upload(text, fileName, lat, lon,  new RequestListener() {

			@Override
			public void onIOException(IOException e) {
				e.printStackTrace();				
			}

			@Override
			public void onError(WeiboException e) {
				e.printStackTrace();

			}

			@Override
			public void onComplete(String response) {
				handler.sendEmptyMessage(0);
			}
		});
	}



}